package cn.itcast.controller;


import cn.itcast.entity.MessageConstant;
import cn.itcast.entity.PageResult;
import cn.itcast.entity.QueryPageBean;
import cn.itcast.entity.Result;
import cn.itcast.pojo.Permission;
import cn.itcast.pojo.Role;
import cn.itcast.service.RoleService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 *  角色管理
 */

@RestController
@RequestMapping("/role")
public class RoleController {


    @Reference
    RoleService roleService;

    /**
     *  新增角色
     * @param role
     * @return
     */
    @RequestMapping("/add.do")
    public Result add(@RequestBody Role role){

        try {//新增角色成功
            roleService.add(role);

        } catch (Exception e) {
            //新增角色失败
            e.printStackTrace();

            return new Result(false, MessageConstant.ADD_ROLE_FAIL);
        }

        return new Result(true, MessageConstant.ADD_ROLE_SUCCESS);
    }


    @RequestMapping("/findAll.do")
    public List<Role> findAll() {

       return roleService.findAll();

    }


    /**
     * 角色管理-分页查询
     * @param queryPageBean
     * @return
     */
    @RequestMapping("/findPage.do")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){


        return roleService.findPage(queryPageBean);

    }

    /**
     * 角色管理-根据角色id查询权限信息
     * @param roleId
     * @return
     */

    @RequestMapping("/findPermissionByRoleId.do")
    public List<Integer> findPermissionByRoleId(Integer roleId){

       return roleService.findPermissionByRoleId(roleId);

    }


    /**
     * 角色管理-查询所有权限
     * @return
     */
    @RequestMapping("/findAllPermission.do")
    public List<Permission> findAllPermission(){

        return roleService.findAllPermission();

    }


    /**
     * 角色管理-给角色添加权限
     * @param roleId
     * @param permissionIds
     * @return
     */
    @RequestMapping("/addPermission.do")
    public Result addPermission(Integer roleId,@RequestBody Integer[] permissionIds){


        try {
            roleService.addPermission(roleId,permissionIds);

        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_PERMISSION_FAIL);
        }

        return new Result(true,MessageConstant.ADD_PERMISSION_SUCCESS);
    }


    /**
     * 角色管理-根据id删除角色
     * @param id
     * @return
     */
    @RequestMapping("/deleteRoleById.do")
    public Result deleteRoleById(Integer id){


        try {
            roleService.deleteRoleById(id);

        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"删除角色失败");
        }

        return new Result(true,"删除角色成功");
    }
}
